import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.odps.udf.UDF;
import com.aliyun.odps.utils.StringUtils;

/**
 * 
 * @author tuchuanqi 解析iherb商品详情页面所需信息
 *
 */
public class SpliderIherbGoods extends UDF {
	private String iherb_url = "https://www.iherb.com";

	public String evaluate(String html) {
		try {
			JSONObject returnObj = new JSONObject();
			if (StringUtils.isNotBlank(html)) {
				Document doc = Jsoup.parse(html);
				// 获取品牌，分类
				Element idEle = doc.getElementById("breadCrumbs");
				if (null != idEle) {
					Elements aTagEle = idEle.getElementsByTag("a");
					StringBuffer categSb = null;
					for (int i = 0; i < aTagEle.size(); i++) {
						String hrefAttr = aTagEle.get(i).attr("href");
						if (StringUtils.isNotBlank(hrefAttr) && hrefAttr.contains("/BrandsAZ")) {
							// 品牌
							++i;
							returnObj.put("brand", aTagEle.get(i).text());
							continue;
						}
						if (StringUtils.isNotBlank(hrefAttr) && hrefAttr.contains("/Categories")) {
							if (null != categSb) {
								categSb.append("@");
							} else {
								categSb = new StringBuffer();
							}
							continue;
						}
						categSb.append(aTagEle.get(i).text()).append("|");
					}
					returnObj.put("category", categSb);
				}

				// 获取图片
				Element imgEle = doc.getElementById("product-image");
				StringBuffer imgSb = new StringBuffer();
				// 获取大图的标签
				Elements elementsByTagA = imgEle.getElementsByTag("a");
				if (null != elementsByTagA && elementsByTagA.size() == 1) {
					String bigImg = elementsByTagA.get(0).attr("href");
					if (StringUtils.isNotBlank(bigImg)) {
						imgSb.append(bigImg).append(",");
					}
				}
				// 获取小图标签
				Elements elementsByTagImg = imgEle.getElementsByTag("img");
				if (null != elementsByTagImg && elementsByTagImg.size() != 0) {
					for (Element ele : elementsByTagImg) {
						String smallImg = ele.attr("src");
						if (StringUtils.isNotBlank(smallImg)) {
							imgSb.append(smallImg).append(",");
						}
					}
				}
				returnObj.put("img", imgSb.toString());

				// 获取商品名称
				Element eleByIdName = doc.getElementById("name");
				if (null != eleByIdName) {
					returnObj.put("name", eleByIdName.text());
				}

				// 获取建议价格
				Element priceEle = doc.getElementById("product-msrp");
				if (null != priceEle) {
					Elements eleByClassVal = priceEle.getElementsByClass("col-xs-15 col-md-16 price");
					String priceValue = null;
					if (null != eleByClassVal && eleByClassVal.size() == 1) {
						priceValue = eleByClassVal.get(0).text();
					}
					if (StringUtils.isNotBlank(priceValue)) {
						returnObj.put("MSRP", priceValue);
					}
				}

				// 获取 包装数量 和 udp代码
				Element elementById = doc.getElementById("product-specs-list");
				if (null != elementById) {
					Elements elementsByTagLi = elementById.getElementsByTag("li");
					if (null != elementsByTagLi && elementsByTagLi.size() != 0) {
						for (Element ele : elementsByTagLi) {
							String text = ele.text();
							if (text.contains("UPC Code:")) {
								Elements elementsByTagSpan = ele.getElementsByTag("span");
								if (null != elementsByTagSpan && elementsByTagSpan.size() == 1) {
									returnObj.put("UPC_Code", elementsByTagSpan.get(0).text());
								}
							} else if (text.contains("Package Quantity:")) {
								String[] split = text.split(":");
								returnObj.put("Package_Quantity", split[1]);
							}
						}
					}
				}

				// 获取产品等级 Product Rank:
				Elements eleByClass = doc.getElementsByClass("best-selling-rank");
				StringBuffer sb = new StringBuffer();
				if (null != eleByClass && eleByClass.size() == 1) {
					Elements elesByTagDiv = eleByClass.get(0).getElementsByTag("div");
					for (int i = 1; i < elesByTagDiv.size(); i++) {
						Element ele = elesByTagDiv.get(i);
						Elements elesByTagStro = ele.getElementsByTag("strong");
						if (null != elesByTagStro && elesByTagStro.size() != 0) {
							for (Element e : elesByTagStro) {
								sb.append(e.text());
							}
						}
						sb.append(",");
					}
				}
				returnObj.put("Product_Rank", sb.toString());

				// 获取产品描述 其他成分
				Elements elementsByClass = doc.getElementsByClass("row item-row");
				StringBuffer sbDescp = new StringBuffer();
				if (null != elementsByClass && elementsByClass.size() == 6) {
					// 产品描述
					Element element = elementsByClass.get(0);

					Elements elementsByTagLi = element.getElementsByTag("li");
					if (null != elementsByTagLi && elementsByTagLi.size() != 0) {
						for (Element e : elementsByTagLi) {
							sbDescp.append(e.text()).append("|");
						}
					}
					Elements elementsByTagP = element.getElementsByTag("p");
					if (null != elementsByTagP && elementsByTagP.size() != 0) {
						for (Element e : elementsByTagP) {
							sbDescp.append(e.text()).append("|");
						}
					}
					returnObj.put("description", sbDescp.toString());

					// 其他成分 可能是一段 也可能是一张表 所以进行判断
					Element elementOther = elementsByClass.get(2);
					// 一段
					Elements elementsP = elementOther.getElementsByTag("p");
					if (null != elementsP && elementsP.size() != 0) {
						returnObj.put("ingredients", elementsP.get(0).text());
					}
					// 一张表
					Elements elementsTab = elementOther.getElementsByTag("table");
					if (null != elementsTab && elementsTab.size() != 0) {
						List<Map<String, String>> trList = new ArrayList<Map<String, String>>();
						Elements elementsTr = elementsTab.get(0).getElementsByTag("tr");
						if (null != elementsTr && elementsTr.size() != 0) {
							// 获取表的每行 第一行为表头 从第二行开始取
							for (int i = 1; i < elementsTr.size(); i++) {
								Map<String, String> tdMap = new HashMap<String, String>();
								// 获取列 有2列或者1列 进行判断
								Elements eleTd = elementsTr.get(i).getElementsByTag("td");
								if (null != eleTd && eleTd.size() == 2) {
									tdMap.put(eleTd.get(0).text(), eleTd.get(1).text());
									trList.add(tdMap);
								} else if (null != eleTd && eleTd.size() == 1) {
									String text = eleTd.get(0).text();
									String[] split = text.split(":");
									tdMap.put(split[0], text);
									trList.add(tdMap);
								}
							}
						}
						returnObj.put("ingredients", JSON.toJSONString(trList));
					}

				}

				// 获取评论链接 content-frame product-details-reviews   暂时获取不到
				Elements eleByClassUrl = doc.getElementsByClass("content-frame product-details-reviews");
				if (null != eleByClassUrl && eleByClassUrl.size() == 1) {
					Elements eleByClassShow = eleByClassUrl.get(0).getElementsByClass("show");
					if (null != eleByClassShow && eleByClassShow.size() == 1) {
						String href = eleByClassShow.get(0).attr("href");
						returnObj.put("comment_url", iherb_url + href);
					}
				}
			}
			return JSON.toJSONString(returnObj);
		} catch (Exception e) {
			e.printStackTrace();
			return "解析错误"+e.getMessage();
		}
	}

}
